<?php

	class source
	{

		var $fw		= null;
		var $sec	= null;

		function source(&$framework, &$security)
		{

			$this->fw	= &$framework;
			$this->sec	= &$security;

			$this->fw->js[] = 'login.js';

			switch($this->fw->do) {

				// register
				case 'register':
					$this->show_registration_form();
					break;

				case 'process_register':
					$this->process_registration_form();
					break;

				case 'confirm':
					$this->process_confirm();
					break;

				case 'check_username':
					$this->process_check_username();
					break;

				// retrieve password
				case 'retrieve':
					$this->show_retrieval_form();
					break;

				case 'retrieve_password':
					$this->process_retrieve();
					break;

				case 'validate':
					$this->process_validate();
					break;

				case 'password':
					$this->process_change_password();
					break;

				// general login
				case 'process_login':
					$this->process_login();
					break;

				default:
					$this->show_login();
					break;

			}

		}

		function process_check_username()
		{
			$this->fw->main_template = null; // ajax mode
			$username	= $_GET['username'];

			if($this->fw->is_username($username)) {
				// valid username
				$sql		= $this->fw->_pq("SELECT COUNT(`member_id`) FROM `#__member` WHERE `member_username` = '%s' LIMIT 1", $username);
				$result		= mysql_query($sql) or die(mysql_error());
				echo (mysql_result($result, 0, 0) == 1) ? 'true' : 'false';
			} else {
				// invalid username;
				echo 'invalid';
			}
		}

		function process_login()
		{

			$username	= $_POST['username'];
			$password	= $_POST['password'];
			$auto_login	= isset($_POST['auto_login']) && $_POST['auto_login'] == '1' ? true : false;

			// Lets do some basic checking
			$error = array();

			if(empty($username))
			{
			}
			elseif(strlen($username) > 20)
			{
			}

			// Checking has been finished. Lets ensure that these details exist in the db

			$sql	= $this->fw->_pq("SELECT member_id FROM #__member WHERE member_username = '%s' AND member_password = MD5('%s') AND member_active = '1' AND member_approved = '1' AND member_approved_date > 0", $username, $password);
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) == 1) {
				$id	= mysql_result($result, 0, 0);
				$this->sec->create_authentication($id);

				if($auto_login) {
					$this->sec->create_auto_login();
				}

				header('location: index.php');
				exit;

			} else {
				// This user doesnt have the privalge to login, or doesnt exist!
				$_SESSION['msg']	= 'Login details could not be found.';
				header('location: index.php');
				exit;
			}
		}

		function process_retrieve()
		{
			$retrieve	= $_POST['retrieve'];

			if($this->fw->is_email($retrieve)) {
				$field = 'email';
			} else {
				$field = 'username';
			}

			// lets check if the peice of retrieve data exists
			$sql	= $this->fw->_pq("SELECT `member_id` FROM `#__member` WHERE `member_". $field ."` = '%s' AND member_active = 1 AND member_approved = 1 LIMIT 1", $retrieve);
			$result	= mysql_query($sql) or die(mysql_error());
			if(mysql_num_rows($result) == 1) {
				$member_id = mysql_result($result, 0, 0);
			}

			if(isset($member_id) && $member = $this->fw->get_member_details($member_id)) {
				// we have a member id! lets generate an email!
				$code	= md5($member['id'] . $member['email'] . $member['username'] . $member['last_login']);
				$url	= $this->fw->config['base_url'] . 'index.php?do=validate&i='. $member['id'] .'&cc='. $code;

				$to			= $member['email'];
				$subject	= 'Retrieve Password';
				$message	= 'To reset your password please visit '. $url;
				$header[]	= 'From: "Movie Manager" <unknown@unknown>';

				$mail		= mail($to, $subject, $message, implode("\r\n", $header));

				if($mail) {
					$_SESSION['msg'] = 'Validation email sent to '. $member['email'] .'. Check your email and follow its instructions';
					header('location: index.php');
					break;
				} else {
					// could not send email
					$this->show_retrieval_form('Unable to send validation email');
				}
			} else {
				// couldn't find a user with these details
				$this->show_retrieval_form('Errors Detected', array('retrieve' => 'Could not find a member with this e-mail address/username'));
			}
		}

		// change the members password (requires validation)
		function process_change_password()
		{
			$member_id	= $_POST['member_id'];
			$cc			= $_POST['cc'];
			$password	= $_POST['password'];
			$cpassword	= $_POST['password_confirm'];

			// we have to revalidate this for security
			$member	= $this->fw->get_member_details($member_id);

			if($member) {
				$code	= md5($member['id'] . $member['email'] . $member['username'] . $member['last_login']);
				if($code == $cc) {
					// lets validate the password
					if(empty($password)) {
						$errors['password'] = 'Field Required';
					} elseif($password != $cpassword) {
						$errors['password'] = 'Passwords do not match';
					}

					if(!isset($errors)) {
						// validation complete, lets update their password
						$sql	= $this->fw->_pq("UPDATE `#__member` SET member_password = MD5('%s'), `updated` = UNIX_TIMESTAMP() WHERE `member_id` = %s", $password, $member_id);
						$result	= mysql_query($sql) or die(mysql_error());
						if(mysql_affected_rows() == 1) {
							$_SESSION['msg'] = 'Password Successfully Updated';
							header('location: index.php');
							exit;
						} else {
							$this->process_validate('Database error. Could not update password');
						}
					} else {
						$this->process_validate('Errors Detected', $errors);
					}
				} else {
					$_SESSION['msg'] = 'Invalid URL';
					header('location: index.php');
					exit;
				}
			} else {
				$_SESSION['msg'] = 'Invalid URL';
				header('location: index.php');
				exit;
			}
		}

		// confirm that the person who has just registered owns the email address they used
		function process_confirm()
		{
			$id	= (int)$_GET['id'];
			$cc	= $_GET['cc'];

			$member = $this->fw->get_member_details($id);
			$code	= md5($member['id'] . $member['username'] . $member['email']);

			if($code === $cc) {
				// details verified, lets update the db, and let them login
				$sql	= $this->fw->_pq("UPDATE `#__member` SET `member_active` = 1, `updated` = UNIX_TIMESTAMP() WHERE `member_id` = %s", $id);
				$result	= mysql_query($sql) or die(mysql_error());
				if($result) {
					// we are done
					$_SESSION['msg'] = 'Account Confirmed. Welcome!';
					header('location: index.php');
					exit;
				} else {
					$_SESSION['msg'] = 'Database error. Could not confirm account';
					header('location: index.php');
					exit;
				}
			} else {
				// the codes do not match!
				$_SESSION['msg'] = 'The confirmation code is not correct and could not be verified';
				header('location: index.php');
				exit;
			}

		}

		function show_login($msg = null, $msg_type = true)
		{

			$this->fw->pc_item('Login', 'Login Screen');

			$this->fw->template	= 'login.form.tpl';

		}

		// show the registration form
		function show_registration_form($err_msg = null, $err = array())
		{

			$reg_type = 'public';

			$this->fw->js[] = 'ajax.js';
			$this->fw->pc_item('Register', 'Create a new account');

			$this->fw->template	= 'login.register.tpl';

			if($this->fw->do == 'process_register') {
				$username	= $_POST['username'];
				$email		= $_POST['email'];
				$reference	= $_POST['reference'];
				$cc			= $_POST['cc'];
			} else {
				$username	= null;
				$email		= isset($_GET['email']) ? $_GET['email'] : null;
				$reference	= isset($_GET['ref']) ? $_GET['ref'] : null;
				$cc			= isset($_GET['cc']) ? $_GET['cc'] : null;
			}

			// is this an invite?
			if(!empty($cc)) {
				// if its a invite lets check it
				$ref_member = $this->fw->get_member_details($reference);
				if($ref_member) {
					$code	= md5($ref_member['id'] . $email . $ref_member['email'] . $ref_member['approve_date']);
					if($cc == $code) {
						$reg_type = 'invite';
					}
				}

			}

			// is this an invite or public registration?
			if($this->fw->config['public_registration'] == '0' && $reg_type == 'pubic') {
				header('location: index.php');
				exit;
			}

			$this->fw->content['username']	= $username;
			$this->fw->content['email']		= $email;
			$this->fw->content['reference']	= $reference;
			$this->fw->content['cc']		= $cc;

		}

		function process_registration_form()
		{

			$reg_type = 'public';

			$username			= $_POST['username'];
			$email				= $_POST['email'];
			$password			= $_POST['password'];
			$password_confirm	= $_POST['confirm_password'];
			$reference			= $_POST['reference'];
			$cc					= $_POST['cc'];

			// is this an invite?
			if(!empty($cc)) {
				// if its a invite lets check it
				$ref_member = $this->fw->get_member_details($reference);
				if($ref_member) {
					$code	= md5($ref_member['id'] . $email . $ref_member['email'] . $ref_member['approve_date']);
					if($cc == $code) {
						$reg_type = 'invite';
					}
				}

			}

			if($this->fw->config['public_registration'] == '0' && $reg_type == 'public') {
				header('location: index.php');
				exit;
			}

			// error checking
			if(!$this->fw->is_username($username)) {
				$errors['username'] = 'Invalid Username';
			} else {
				$sql		= $this->fw->_pq("SELECT COUNT(`member_id`) FROM `#__member` WHERE `member_username` = '%s' LIMIT 1", $username);
				$result		= mysql_query($sql) or die(mysql_error());
				if(mysql_result($result, 0, 0) == 1) {
					$errors['username'] = 'Username taken';
				}
			}

			if(!$this->fw->is_email($email)) {
				$errors['email']	= 'Invalid E-mail Address';
			} else {
				$sql		= $this->fw->_pq("SELECT COUNT(`member_id`) FROM `#__member` WHERE `member_email` = '%s' LIMIT 1", $email);
				$result		= mysql_query($sql) or die(mysql_error());
				if(mysql_result($result, 0, 0) == 1) {
					$errors['email'] = 'E-mail Address taken';
				}
			}

			if(empty($password)) {
				$errors['password'] = 'Field Required';
			} elseif($password != $password_confirm) {
				$errors['password'] = 'Did not match';
			}

			// get the reference id, or fail
			if(!empty($reference)) {
				// what type of reference is it?
				if(is_numeric($reference)) {
					$reference = (int)$reference;
					$sql	= $this->fw->_pq("SELECT COUNT(`member_id`) FROM `#__member` WHERE `member_id` = %s LIMIT 1", $reference);
					$result	= mysql_query($sql) or die(mysql_error());
					if(mysql_result($result, 0, 0) == 0) {
						$errors['reference'] = 'Reference ID can\'t be found';
					}
				} elseif($this->fw->is_email($reference)) {
					$sql		= $this->fw->_pq("SELECT `member_id` FROM `#__member` WHERE `member_email` = '%s' LIMIT 1", $reference);
					$result		= mysql_query($sql) or die(mysql_error());
					if(mysql_num_rows($result) == 0) {
						$errors['reference'] = 'E-mail Address taken';
					} else {
						$reference = (int)mysql_result($result, 0, 0);
					}
				} elseif($this->fw->is_username($reference)) {
					$sql		= $this->fw->_pq("SELECT `member_id` FROM `#__member` WHERE `member_username` = '%s' LIMIT 1", $reference);
					$result		= mysql_query($sql) or die(mysql_error());
					if(mysql_num_rows($result) == 0) {
						$errors['reference'] = 'E-mail Address taken';
					} else {
						$reference = (int)mysql_result($result, 0, 0);
					}
				} else {
					$reference = null;
				}
			}

			if(!isset($errors)) {
				// all checking has been done, create the account
				$sql	= $this->fw->_pq("INSERT INTO `#__member` (`member_username`, `member_password`, `member_email`, `member_active`, `member_approved`, `member_approved_date`, `referer_id`, `created`, `updated`, `pref_public_collection`, `pref_imdb_window`) VALUES ('%s', MD5('%s'), '%s', -1, 1, UNIX_TIMESTAMP(), %s, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 1, 1);", $username, $password, $email, $reference);
				$result	= mysql_query($sql) or die(mysql_error());

				if(mysql_affected_rows() == 1)  {
					$member_id = mysql_insert_id();
					// lets send an e-mail to this person
					$code	= md5($member_id . $username . $email);
					$url = $this->fw->config['base_url'] . 'index.php?do=confirm&id='. $member_id .'&cc='. $code;
					$message = $url;
					$headers = 'From: "Movie Manager" <benrowe@exemail.com.au>';
					$mail = mail($email, 'Activation Required', $message, $headers);
					if($mail) {
						$_SESSION['msg'] = 'Registration Successful. An email has been sent to '. $email .' to confirm your details';
						header('location: index.php');
						exit;
					} else {
						$this->show_registration_form('Unable to e-mail confirmation to '. $email);
					}
				} else {
					// query failed
					$this->show_registration_form('Database error occured');
				}

			} else {
				// errors discovered
				$this->show_registration_form('Errors Found', $errors);
			}
		}

		// show the form to retrieve the password
		function show_retrieval_form()
		{

			$this->fw->pc_item('Retrieve Password', 'obtain a new password if you can not remember your existing password', 'index.php?do=retrieve');
			$this->fw->template	= 'login.retrieve.tpl';

		}

		// part of the retrieve password. URL generated from email. validate user and let them reset their password
		function process_validate($err_msg = null, $err = array())
		{

			if($this->fw->do == 'password') {
				$member_id	= $_POST['member_id'];
				$cc			= $_POST['cc'];
			} else {
				$member_id	= (int)$_GET['i'];
				$cc			= $_GET['cc'];
			}

			// validate their details and the code

			$member		= $this->fw->get_member_details($member_id);

			if($member) {
				// lets rebuild the validation code
				$code	= md5($member['id'] . $member['email'] . $member['username'] . $member['last_login']);
				if($code == $cc) {
					// ok! we are in!
					// show a form to allow them to reset their password
					$this->fw->template = 'login.reset_password.tpl';

					$this->fw->content['member_id'] = $member_id;
					$this->fw->content['cc']		= $cc;
				} else {
					$_SESSION['msg'] = 'Invalid URL';
					header('location: index.php');
					exit;
				}
			} else {
				// this member id doesn't exist with the database
				$_SESSION['msg'] = 'Invalid URL';
				header('location: index.php');
				exit;
			}
		}
	}

?>